package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.LearnRecordBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wo on 2015/11/10.
 */
public class KnowledgePointView extends LinearLayout implements View.OnClickListener{
    private Activity mContext;
    private View mView1, mView2;
    private PlayControlView mPlayController;
    private TextView mWordView;

    private TextView mTipDesc;
    private TextView mTipWord, mTipShape;
    private TextView mTipExample;

    private Cursor cursor;
    private List<AppDataBean> mDataList;
    private int currentPosition = 0;
    private int lessonType = 6;

    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;
    private ViewGroup mContainer;
    private View mPointBottomView, mTipBottomView;

    public KnowledgePointView(Context context) {
        super(context);
        mContext = (Activity)context;
        Typeface type = Typeface.createFromAsset(getContext().getAssets(), "fonts/hanyupinyin.ttf");
        View view = LayoutInflater.from(context).inflate(R.layout.knowledge_container_view, null);
        mContainer = (ViewGroup) view.findViewById(R.id.knowledge_container);
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

        mView1 = mContainer.findViewById(R.id.knowledge_container_layout01);
        mView2 = mContainer.findViewById(R.id.knowledge_container_layout02);

        mPlayController = (PlayControlView) mContainer.findViewById(R.id.knowlegde_point_play_control);
        mWordView = (TextView) mContainer.findViewById(R.id.knowledge_point_text);
        mWordView.setTypeface(type);

        mTipDesc = (TextView)mContainer.findViewById(R.id.knowledge_tip_desc);
        mTipWord = (TextView)mContainer.findViewById(R.id.knowledge_tip_word);
        mTipWord.setTypeface(type);
        mTipShape =  (TextView)mContainer.findViewById(R.id.knowledge_tip_shape);
        mTipShape.setTypeface(type);
        mTipExample = (TextView)mContainer.findViewById(R.id.knowledgt_tip_example);
        mTipExample.setTypeface(type);

        mPointBottomView = mContainer.findViewById(R.id.knowledge_point_bottom_view);
        mPointBottomView.setOnClickListener(this);
        mTipBottomView = mContainer.findViewById(R.id.knowledge_tip_bottom_view);
        mTipBottomView.setOnClickListener(this);

        this.addView(mContainer);
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while(cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            mDataList.add(d);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        Logger.e("xionghy: " + mDataList.get(currentPosition).toString());
        updateViewData();
    }

    private void updateViewData() {
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        AppDataBean data = mDataList.get(currentPosition);
        mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        mPlayController.setStandardUrl(mMp3SourceDir);
        mPlayController.setPlayRecordVisibility(View.INVISIBLE);
//        mPlayController.playStandard();
        mWordView.setText(data.getChinese());
        updateView2Data();
        addLearnRecord(data);
        addAnimation();
    }

    private void updateView2Data() {
        AppDataBean data = mDataList.get(currentPosition);
        mTipDesc.setText(getResources().getString(R.string.ps) + data.getPhone().replace("|", ", "));
        String word = data.getPinyin().split(" ")[0];
        mTipWord.setText(word);
        String s = data.getPinyin().substring(4,5);
        mTipShape.setText(s);
        mTipExample.setText(getResources().getString(R.string.example) + data.getTone().replace("|", ", ") + getResources().getString(R.string.deng));
        initTipDesc();
    }

    // 每个空间都添加一种动画
    long durationMillis = 1000, delayMillis = 0;
    private Animation wordViewAnimation = null;
    private Animation.AnimationListener wordViewAnimListener = null;
    private void addAnimation() {
        if (mWordView != null) {
            wordViewAnimListener = new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }
                @Override
                public void onAnimationEnd(Animation animation) {
                    mPlayController.playStandard();
                }
                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            };
            wordViewAnimation = scaleIn(mWordView, durationMillis, delayMillis, wordViewAnimListener);
            mWordView.post(new Runnable() {
                @Override
                public void run()  {
                    wordViewAnimation.start();
                }
            });

        }
    }

    private Animation scaleIn(View view, long durationMillis, long delayMillis, Animation.AnimationListener l){
        ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(animation);
        animation.setAnimationListener(l);
        animation.cancel();
        return animation;
    }

    private void initTipDesc() {
        String s = getResources().getString(R.string.ps) + " ";
        if (currentPosition<3) {
            s += getResources().getString(R.string.tip_0);
        } else if (currentPosition < 5) {
            s += getResources().getString(R.string.tip_1);
        } else if (currentPosition < 7) {
            s += getResources().getString(R.string.tip_2);
        } else if (currentPosition < 10) {
            s += getResources().getString(R.string.tip_3);
        } else if (currentPosition < 13) {
            s += getResources().getString(R.string.tip_4);
        } else if (currentPosition < 16) {
            s += getResources().getString(R.string.tip_5);
        } else if (currentPosition < 20) {
            s += getResources().getString(R.string.tip_6);
        } else if (currentPosition < 24) {
            s += getResources().getString(R.string.tip_7);
        } else if (currentPosition < 28) {
            s += getResources().getString(R.string.tip_8);
        } else if (currentPosition < 31) {
            s += getResources().getString(R.string.tip_9);
        } else if (currentPosition < 34) {
            s += getResources().getString(R.string.tip_10);
        } else if (currentPosition < 37) {
            s += getResources().getString(R.string.tip_11);
        } else if (currentPosition < 40) {
            s += getResources().getString(R.string.tip_12);
        } else if (currentPosition < 43) {
            s += getResources().getString(R.string.tip_13);
        } else if (currentPosition < 46) {
            s += getResources().getString(R.string.tip_14);
        }
        mTipDesc.setText(s);
    }

    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        mPlayController.resetProgressBar();
        currentPosition ++;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            Utils.showDialog(mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
        }
    }

    public void beforeWord() {
        if (currentPosition <= 0)
            return;
        mPlayController.resetProgressBar();
        currentPosition --;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            mNextListener.onLessonChanged(lessonType - 1);
        }
    }

    public void setListener(LessonProgressInterface listener) {  mListener = listener; }

    public void setNextListener(NextLessonInterface listener) { mNextListener = listener; }

    public void setLessonType(int lesson) { lessonType = lesson; }

    public void setVolumeListener(VolumeListener l) { mPlayController.setVolumeListener(l); }

    public void setRecordListener(RecordStatusListener l) { mPlayController.setRecordListener(l); }

    public void onDestroy() {
        if (mPlayController != null) {
            mPlayController.destory();
        }
        if (cursor != null)
            cursor.close();
        SimpleRecordUtil.getInstance(mContext).stopPlayer();
        SimpleRecordUtil.getInstance(mContext).stopRecorder();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.knowledge_point_bottom_view) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = mContainer.getWidth() / 2f;
            float centerY = mContainer.getHeight() / 2f;
            // 构建3D旋转动画对象，旋转角度为0到90度，这使得ListView将会从可见变为不可见
            final Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90, centerX, centerY, 310.0f, true);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            // 设置动画的监听器
            rotation.setAnimationListener(new TurnToView1());
            mContainer.startAnimation(rotation);
        } else if (id == R.id.knowledge_tip_bottom_view) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = mContainer.getWidth() / 2f;
            float centerY = mContainer.getHeight() / 2f;
            // 构建3D旋转动画对象，旋转角度为360到270度，这使得ImageView将会从可见变为不可见，并且旋转的方向是相反的
            final Rotate3dAnimation rotation = new Rotate3dAnimation(360, 270, centerX, centerY, 310.0f, true);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            // 设置动画的监听器
            rotation.setAnimationListener(new TurnToView2());
            mContainer.startAnimation(rotation);
        }
    }

    class TurnToView1 implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = mContainer.getWidth() / 2f;
            float centerY = mContainer.getHeight() / 2f;
            mView1.setVisibility(View.GONE);
            // 将ImageView显示
            mView2.setVisibility(View.VISIBLE);
            mView2.requestFocus();
            // 构建3D旋转动画对象，旋转角度为270到360度，这使得ImageView将会从不可见变为可见
            final Rotate3dAnimation rotation = new Rotate3dAnimation(270, 360, centerX, centerY,
                    310.0f, false);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            mContainer.startAnimation(rotation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * 注册在ImageView点击动画中的动画监听器，用于完成ImageView的后续动画。
     */
    class TurnToView2 implements Animation.AnimationListener {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        /**
         * 当ImageView的动画完成后，还需要再启动ListView的动画，让ListView从不可见变为可见
         */
        @Override
        public void onAnimationEnd(Animation animation) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = mContainer.getWidth() / 2f;
            float centerY = mContainer.getHeight() / 2f;
            // 将ImageView隐藏
            mView2.setVisibility(View.GONE);
            // 将ListView显示
            mView1.setVisibility(View.VISIBLE);
            mView1.requestFocus();
            // 构建3D旋转动画对象，旋转角度为90到0度，这使得ListView将会从不可见变为可见，从而回到原点
            final Rotate3dAnimation rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
                    310.0f, false);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            mContainer.startAnimation(rotation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

    }

    private void addLearnRecord(AppDataBean data) {
        LearnRecordBean bean = new LearnRecordBean();
        bean.setChinese(data.getChinese());
        bean.setLearnedTimes(1);
        bean.setLearnType(lessonType + "");
        bean.setRecordID(data.getType() + "|" + data.getWeight());
        bean.setTimestamp(System.currentTimeMillis() + "");
        DBHelper.getInstance(mContext).insertLearnRecord(bean);
    }

}